import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import { PROJECT_BUG_STATUS, PROJECT_BUG_TYPE, PROJECT_BUG_GROUP, PRIORUTY_LEVEL } from '@/consts/project'
import { Button, Space, Table, Tag, Tooltip } from 'antd'
import { CheckCircleOutlined, CloseCircleOutlined, SendOutlined, IssuesCloseOutlined, CopyOutlined } from '@ant-design/icons'
import { useState, useEffect } from 'react'
import styles from './styles.less'
import { connect, history } from 'umi';
import UserBrief from '@/components/UserBrief'
import CheckActon from '../../CheckActoin'
import ActionDropdown from '@/components/ActionDropdown';
import BugAddModal from './../BugAddModal'
import PriorityLevel from '../../PriorityLevel'
import { pageBug ,closeBug} from '@/services/project/bug'
import { formetTime_MDHm } from '@/utils/dateUtils'
import ProjectQaSelect from '@/pages/projects/components/ProjectQA/ProjectQaSelect'
import { BugConfirmModal, BugFixModal, BugToUserChangeModal } from './../BugDetail/BugAction'

export const BugStatus = (props) => {

    const {
        status
    } = props

    if (status || status === 0) {
        return <Tag color={PROJECT_BUG_STATUS[status].color}>{PROJECT_BUG_STATUS[status].name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}

export const ConfirmStatus = ({ confirmStatus }) => {
    return confirmStatus === 1 ? <span style={{ color: "#73d13d" }}>是</span> : '否';
}

const BugPage = (props) => {
    const {
        projectId,
        onQueryParamChange,
        queryInitParams,
        projectPermission,
        myInfo
    } = props

    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 10,
        inStatus:["1","2","3","4"]
    })
    const [showAddBugModalVisiable, setShowAddBugModalVisiable] = useState(false)
    const [bugPage, setBugPage] = useState()
    const [bugPageLoading, setBugPageLoading] = useState()

    const [selectChangeToUserBugDetail, setSelectChangeToUserBugDetail] = useState();
    const [selectConfirmBugDetail, setSelectConfirmBugDetail] = useState()
    const [selectFixBugDetail, setSelectFixBugDetail] = useState(false)
    const [selectCopyId,setSelectCopyId] = useState();
    const [permission, setPermission] = useState({})

    useEffect(() => {
        let initParam = {
            ...params,
            ...queryInitParams
        }
        setParams(initParam)
        if (projectId) {
            queryBugPage(initParam)
        }

    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.bug
        })
    }, [projectPermission])

    useEffect(() => {
        if (selectCopyId) {
            setShowAddBugModalVisiable(selectCopyId)
        }
    },[selectCopyId])

    const onParamChange = (param, doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        if (onQueryParamChange) {
            onQueryParamChange(newParams)
        }
        if (doQuery) {
            queryBugPage(newParams)
        }
    }

    const queryBugPage = (queryParams) => {
        setBugPageLoading(true)
        pageBug(projectId, (queryParams || params)).then(({ data }) => {
            setBugPage(data)
            setBugPageLoading(false)
        })
    }

    const closeLocalBug = (bugId) => {
        closeBug(projectId, bugId, {})
            .then(({ data }) => {
                queryBugPage()
            })
    }

    const showBugDetail = (bug) => {
        history.push(`/projects/${projectId}/bug/${bug.id}`)
    }

    const saveBug = () => {
        queryBugPage();
        setSelectCopyId(null)
        setShowAddBugModalVisiable(false);
    }

    const onChangeToUser = (bug) => {
        setSelectChangeToUserBugDetail(bug)
    }
    const onChangeToUserSuccess = () => {
        queryBugPage();
    }

    const queryItems = [

        {
            name: "inStatus",
            label: "状态",
            isMain: true,
            type: "tagSelect",
            options: ArrayUtils.jsonToArray(PROJECT_BUG_STATUS).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "inToUserId",
            label: "指派给",
            isMain: false,
            span: 8,
            type: "userSelect",
        },
        {
            name: "inUserId",
            label: "负责人",
            isMain: false,
            span: 8,
            type: "userSelect",
        },
        {
            name: "inFixUserId",
            label: "解决人",
            isMain: false,
            span: 8,
            type: "userSelect",
        },
        {
            name: "likeName",
            label: "名称",
            isMain: false,
            span: 8,
            type: "input",
        },
        {
            name: "inGroupName",
            label: "归属",
            isMain: false,
            span: 8,
            type: "select",
            options: ArrayUtils.jsonToArray(PROJECT_BUG_GROUP).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "inType",
            label: "类型",
            isMain: false,
            span: 8,
            type: "select",
            options: ArrayUtils.jsonToArray(PROJECT_BUG_TYPE).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "inPriorityLevel",
            label: "优先级",
            isMain: false,
            span: 8,
            type: "select",
            options: ArrayUtils.jsonToArray(PRIORUTY_LEVEL).map((item) => ({
                value: item.key,
                label: item.value.name
            }))
        },
        {
            name: "inProjectQaItemId",
            label: "测试项",
            isMain: false,
            span: 8,
            type: "custom",
            render: () => {
                return <ProjectQaSelect
                    onChange={(value) => {
                        onParamChange({
                            inProjectQaItemId: value
                        }, true)
                    }}
                    allowClear={true}
                    ismultiple={true}
                    projectId={projectId} />
            }
        },
        {
            name: "confirmStatus",
            label: "确认",
            isMain: false,
            span: 8,
            type: "radio",
            options: [{
                value: 0,
                label: "未确认"
            }, {
                value: 1,
                label: "已确认"
            }]
        },
    ]

    const actionHeader = [
        <ActionDropdown
            key="actions"
            status={params?.isArchived && "filter"}
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />,
        permission.add && <Button type="primary" size="small" onClick={() => {
            setShowAddBugModalVisiable(true)
        }}>
            新增
        </Button>,
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />,
        <CheckActon
            check={params?.userId === myInfo.id}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        inToUserId: myInfo.id
                    }, true)
                } else {
                    onParamChange({
                        inToUserId: undefined
                    }, true)
                }
            }}
            label={'指派给我的'}
        />
    ]

    const tableColumns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: "400px",
            fixed: 'left',
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => record.moduleName ? `[${record.moduleName}]${record.name}` : record.name,
            sorter: (a, b) => a.name.localeCompare(b.name),
        },
        {
            title: '归属',
            dataIndex: 'groupName',
            key: 'groupName',
            width: "64px",
            sorter: (a, b) => a.groupName.localeCompare(b.groupName),
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: "80px",
            render: (text, record) => PROJECT_BUG_TYPE[record.type] && PROJECT_BUG_TYPE[record.type].name
        },
        {
            title: '优先级',
            dataIndex: 'priorityLevel',
            key: 'priorityLevel',
            width: "80px",
            sorter: (a, b) => a.priorityLevel - b.priorityLevel,
            render: (text, record) => <PriorityLevel priorityLevel={record.priorityLevel}></PriorityLevel>
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: "80px",
            sorter: (a, b) => a.status - b.status,
            render: (text, record) => <BugStatus status={record.status}></BugStatus>
        },
        {
            title: '测试项',
            dataIndex: 'projectQaItemId',
            key: 'projectQaItemId',
            width: "100px",
            ellipsis: {
                showTitle: true
            },
            render: (text, record) => record.projectQaItem?.name
        },
        {
            title: '负责人',
            dataIndex: 'userId',
            key: 'userId',
            width: "100px",
            ellipsis: true,
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '指派给',
            dataIndex: 'toUserId',
            key: 'toUserId',
            width: "100px",
            render: (text, record) => record.toUser && <UserBrief user={record.toUser}></UserBrief>
        },
        {
            title: '确认',
            dataIndex: 'confirmStatus',
            key: 'confirmStatus',
            width: "40px",
            render: (text, record) => <ConfirmStatus confirmStatus={record.confirmStatus} />
        },
        {
            title: '解决者',
            dataIndex: 'fixUserId',
            key: 'fixUserId',
            width: "100px",
            render: (text, record) => record.fixUser && <UserBrief user={record.fixUser}></UserBrief>,
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: "96px",
            sorter: (a, b) => a.createTime.localeCompare(b.createTime),
            defaultSortOrder: 'descend',
            render: (text, record) => formetTime_MDHm(record.createTime)
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: "96px",
            render: (text, record) => renderBugAction(record)
        }
    ]

    const renderBugAction = (record) => {
        let canConfirm = (record.confirmStatus === 0) && ((myInfo.id === record.toUserId) || (myInfo.id === record.userId) || permission?.manage);
        let canToUser = (record.status !== 5) && ((myInfo.id === record.toUserId) || (myInfo.id === record.userId) || permission?.manage );
        let canFix = (record.status === 1 || record.status === 2 || record.status === 4) && ((myInfo.id === record.toUserId) || permission?.manage);
        let canClose = (record.status === 3) && ((myInfo.id === record.toUserId) || permission?.manage);

        return (<Space>
            { canConfirm && <Tooltip placement="bottom" title={'确认'}>
                <IssuesCloseOutlined className={styles.actionItem} onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    setSelectConfirmBugDetail(record)
                }} />
            </Tooltip>}
            { canToUser && <Tooltip placement="bottom" title={'指派给'}>
                <SendOutlined className={styles.actionItem} onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    onChangeToUser(record)
                }} />
            </Tooltip>}
            { canFix && <Tooltip placement="bottom" title={'解决'}>
                <CheckCircleOutlined className={styles.actionItem} onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    setSelectFixBugDetail(record)
                }}/>
            </Tooltip>}
            { canClose && <Tooltip placement="bottom" title={'关闭'}>
                <CloseCircleOutlined className={styles.actionItem} onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    closeLocalBug(record.id)
                }} />
            </Tooltip>}
            <Tooltip placement="bottom" title={'拷贝'}>
                <CopyOutlined className={styles.actionItem} onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    setSelectCopyId(record.id)
                }} />
            </Tooltip>
        </Space>)
    }

    const filterColumn = (tableColumns) => {
        // if (tableColumns) {
        //     return tableColumns.filter(column => column.key === 'name'
        //         || column.key === 'status'
        //     )
        // }
        return tableColumns;
    }
    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    scroll={{ x: 1200 }}
                    onChange={(pagination, filters, sorter) => {
                        console.log(pagination, sorter)
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={bugPageLoading}
                    dataSource={bugPage && bugPage.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize,
                        total: bugPage && bugPage.count,
                        current: bugPage && bugPage.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showBugDetail(record)
                            }
                        }
                    }}
                >
                </Table>
            }
        />
        <BugToUserChangeModal bugDetail={selectChangeToUserBugDetail}
            onSuccess={onChangeToUserSuccess}
            onCancel={() => setSelectChangeToUserBugDetail(null)} />
        <BugConfirmModal bugDetail={selectConfirmBugDetail}
            onSuccess={onChangeToUserSuccess}
            onCancel={() => setSelectConfirmBugDetail(null)} />
        <BugFixModal bugDetail={selectFixBugDetail}
            myInfo={myInfo}
            onSuccess={onChangeToUserSuccess}
            onCancel={() => setSelectFixBugDetail(null)} />
        <BugAddModal
            visible={showAddBugModalVisiable}
            projectId={projectId}
            copyBugId={selectCopyId}  
            onCancel={() => {
                setShowAddBugModalVisiable(false)
            }}
            onSaveSuccess={() => {
                saveBug(false)
            }}
        />
    </>
}


export default connect(({ user }) => ({
    myInfo: user.myInfo
}))(BugPage);